package com.hht;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo {

	public static void main(String[] args) throws Exception {
		
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		
		Future<Long> result = forkJoinPool.submit(new NTask(0, 1000001));
		System.out.println(result.get());
		
		forkJoinPool.shutdown();
	}
}

class NTask extends RecursiveTask<Long> {

	static final int THRESHOLD = 1000;
	
	private int begin, end;
	
	public NTask(int begin, int end) {
		this.begin = begin;
		this.end = end;
	}
	
	@Override
	protected Long compute() {
		
		long sum = 0;
		if((end - begin) <= THRESHOLD) {
			for(int i=begin;i<end;i++) {
				sum += i;
			}
		}else {
			int mid = (begin + end) / 2;
			NTask left = new NTask(begin, mid);
			left.fork();
			NTask right = new NTask(mid + 1, end);
			right.fork();
			
			Long lr = left.join();
			System.out.println(begin + "-" + mid + ":" + lr);
			Long rr = right.join();
			System.out.println(mid + "-" + end + ":" + rr);
			
			sum = lr + rr;
		}
		return sum;
	}
}